package com.ccsc.auth.cas.service;

import com.ccsc.auth.cas.dao.AccountDao;
import com.ccsc.auth.cas.entity.*;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.jasig.cas.authentication.UsernamePasswordCredential;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;

/**
 * Created by XingWen on 2017/3/2.
 */

@Service
public class UserService {
    @Autowired
    private AccountDao accountDao;

    @Autowired
    private MyPasswordEncoder myPasswordEncoder;

    public UserEntity verifyAccount(UsernamePasswordCredential transformedCredential){
        String type = transformedCredential.getType();
        String username = transformedCredential.getUsername();
        String password = transformedCredential.getPassword();

        UserEntity userEntity = null;

        switch (type){
            case "1":
                userEntity = accountDao.verifyAccount(username, myPasswordEncoder.encode(password));
                break;
            case "2":
                userEntity = accountDao.verifyAccountByTel(username);
                break;
        }

        return userEntity;
    }

    public SysUserEntity verifySysAccount(UsernamePasswordCredential transformedCredential){
        String type = transformedCredential.getType();
        String username = transformedCredential.getUsername();
        String password = transformedCredential.getPassword();

        SysUserEntity sysUserEntity = accountDao.verifySysAccount(username, myPasswordEncoder.encode(password));


        return sysUserEntity;
    }

    public SysUserEntity getSysUserInfo(String userId){
        try{
            //KMGA修改为username
            //SysUserEntity sysUserEntity = accountDao.getSysUserByUserId(userId);
            SysUserEntity sysUserEntity = accountDao.getSysUserByUserName(userId);
            List<SysSystemEntity> list = Lists.newArrayList();
            if (sysUserEntity.getSystemType().equals(9)){
                list = accountDao.getSysSystems();
            }else{
                SysSystemEntity sysSystemEntity = accountDao.getSysSystemBySystemId(String.valueOf(sysUserEntity.getSystemType()));
                list.add(sysSystemEntity);
            }
            sysUserEntity.setSystem(list);
            return sysUserEntity;
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            return null;
        }
    }

    public Boolean validAccessSystem(String username){
        return true;
    }

    public UserEntity getUserInfo(String userId){
        try{
            UserEntity userEntity = accountDao.getUserByUserId(userId);
            List<RoleEntity> roleEntityList = Lists.newArrayList();
            List<ResourceEntity> resourceEntityList = Lists.newArrayList();

            if(userEntity!=null && userEntity.getUserId() != null){
                roleEntityList = accountDao.getRoleByUserId(userEntity.getUserId());
            }

            if(roleEntityList!=null && roleEntityList.size() > 0){
                for(RoleEntity roleEntity : roleEntityList){
                    List<ResourceEntity> resourceEntitys = accountDao.getResourceByRoleId(roleEntity.getRoleId());
                    resourceEntityList.addAll(resourceEntitys);
                }
            }

            userEntity.setRoles(roleEntityList);
            userEntity.setSystems(classifyResource(resourceEntityList));

            List<SystemEntity> systemEntityList = accountDao.getSystems();
            List<SystemEntity> perSysEntityList = userEntity.getSystems();

            userEntity.setSystems(matchSystemList(systemEntityList, perSysEntityList));

            return userEntity;
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            return null;
        }
    }

    private List<SystemEntity> classifyResource(List<ResourceEntity> resourceEntityList){
        List<SystemEntity> systemEntityList = Lists.newArrayList();
        Map<Integer, Set<ResourceEntity>> resourceMap = Maps.newHashMap();
        Map<Integer, SystemEntity> systemEntityMap = Maps.newHashMap();
        for(ResourceEntity resourceEntity : resourceEntityList){
            SystemEntity systemEntity = new SystemEntity();
            systemEntity.setSystemId(resourceEntity.getSystemId());
            systemEntity.setSystemName(resourceEntity.getSystemName());
            systemEntity.setSystemDescription(resourceEntity.getSystemDescription());
            systemEntity.setSystemIdentifier(resourceEntity.getSystemIdentifier());
            systemEntity.setSystemUrl(resourceEntity.getSystemUrl());
            systemEntity.setSortSeq(resourceEntity.getSortSeq());
            systemEntityMap.put(resourceEntity.getSystemId(), systemEntity);

            if(resourceMap.containsKey(resourceEntity.getSystemId())){
                Set<ResourceEntity> resourceEntitySet = resourceMap.get(resourceEntity.getSystemId());
                resourceEntitySet.add(resourceEntity);
                resourceMap.put(resourceEntity.getSystemId(), resourceEntitySet);
            }
            else {
                Set<ResourceEntity> resourceEntitySet = Sets.newHashSet();
                resourceEntitySet.add(resourceEntity);
                resourceMap.put(resourceEntity.getSystemId(), resourceEntitySet);
            }
        }

        for (Map.Entry<Integer, Set<ResourceEntity>> entry : resourceMap.entrySet()) {
            SystemEntity systemEntity = systemEntityMap.get(entry.getKey());
            systemEntity.setResources(Lists.newArrayList(entry.getValue()));
            systemEntityList.add(systemEntity);
        }
        return systemEntityList;
    }

    private List<SystemEntity> matchSystemList(List<SystemEntity> allSystemList, List<SystemEntity> perSystemEntityList){
        List<SystemEntity> list = perSystemEntityList;
        Set<Integer> sysSet = Sets.newHashSet();

        for(SystemEntity systemEntity : perSystemEntityList){
            sysSet.add(systemEntity.getSystemId());
        }

        if(allSystemList!=null && allSystemList.size()>0){
            for(SystemEntity systemEntity : allSystemList){
                if(!sysSet.contains(systemEntity.getSystemId())){
                    list.add(systemEntity);
                }
            }
        }

        Collections.sort(list, new Comparator<SystemEntity>() {
            @Override
            public int compare(SystemEntity o1, SystemEntity o2) {
                return o1.getSortSeq().compareTo(o2.getSystemId());
            }
        });

        return list;
    }
}
